package edu.ccut.saturn.studio.naviagtor.wizard.project;

import java.util.Map;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnValidation;
import edu.ccut.saturn.studio.database.model.DBConnection;
import edu.ccut.saturn.studio.database.ui.ManageConnectionDialog;
import edu.ccut.saturn.studio.database.ui.ViewerDBConContentProvider;
import edu.ccut.saturn.studio.server.dialog.NewSaturnServerDialog;
import edu.ccut.saturn.studio.server.model.SaturnServer;
import edu.ccut.saturn.studio.server.model.SaturnServerModel;

public class SaturnProjectNewWizardPage extends WizardPage {
	private Text userNameText;
	private Text pwdText;
	private Text urlText;
	private Text driverText;
	private Text databaseTypeText;
	private Text serLocText;
	private Text webConText;
	private Text serTypeText;
	private Combo serverCombo;
	private ComboViewer dataConCombo;
	private Text projectName;
	private Text versionText;
	private Text companyName;

	private String dbConName;
	private String serverName;

	private Map<String, SaturnServer> saturnServers = null;

	private ViewerDBConContentProvider vcp;

	public SaturnProjectNewWizardPage() {
		super(Messages.getString("SaturnProjectNewWizardPage.createcaseproject")); //$NON-NLS-1$
		setTitle(Messages
				.getString("SaturnProjectNewWizardPage.createcaseproject")); //$NON-NLS-1$
		setDescription(Messages
				.getString("SaturnProjectNewWizardPage.assistcreateSaturncaseproject")); //$NON-NLS-1$
	}

	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);
		setControl(container);

		final Label blankLabel = new Label(container, SWT.NONE);
		final GridData gd_blank = new GridData(SWT.FILL, SWT.CENTER, true,
				false, 5, 1);
		blankLabel.setLayoutData(gd_blank);

		final Label label = new Label(container, SWT.NONE);
		label.setText(Messages
				.getString("SaturnProjectNewWizardPage.projectname")); //$NON-NLS-1$

		projectName = new Text(container, SWT.BORDER);
		projectName.setTextLimit(50);
		final GridData gd_projectName = new GridData(SWT.FILL, SWT.CENTER,
				true, false, 2, 1);
		projectName.setLayoutData(gd_projectName);
		projectName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setText(Messages
				.getString("SaturnProjectNewWizardPage.editionid")); //$NON-NLS-1$

		versionText = new Text(container, SWT.BORDER);
		versionText.setTextLimit(50);
		final GridData gd_versionText = new GridData(SWT.FILL, SWT.CENTER,
				true, false, 2, 1);
		versionText.setLayoutData(gd_versionText);
		versionText.setText("1.0.0"); //$NON-NLS-1$
		versionText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setText(Messages
				.getString("SaturnProjectNewWizardPage.supplier")); //$NON-NLS-1$

		companyName = new Text(container, SWT.BORDER);
		companyName.setTextLimit(50);
		final GridData companyNameText = new GridData(SWT.FILL, SWT.CENTER,
				true, false, 2, 1);
		companyName.setLayoutData(companyNameText);
		// companyName.setText("SATURN"); //$NON-NLS-1$
		companyName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		final Label dataConLabel = new Label(container, SWT.NONE);
		dataConLabel
				.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
		dataConLabel.setText(Messages
				.getString("SaturnProjectNewWizardPage.datalink")); //$NON-NLS-1$

		dataConCombo = new ComboViewer(container, SWT.READ_ONLY);
		final GridData gd_dataConCombo = new GridData(SWT.FILL, SWT.TOP, true,
				false);
		gd_dataConCombo.horizontalSpan = 1;
		dataConCombo.getCombo().setLayoutData(gd_dataConCombo);
		vcp = new ViewerDBConContentProvider();
		dataConCombo.setContentProvider(vcp);
		dataConCombo
				.addSelectionChangedListener(new ISelectionChangedListener() {
					public void selectionChanged(
							SelectionChangedEvent selectionchangedevent) {
						validate();
						Object obj = ((IStructuredSelection) selectionchangedevent
								.getSelection()).getFirstElement();
						if (obj instanceof DBConnection) {
							updateDBInfo((DBConnection) obj);
						}
						setDbConName(getDBConnectionName());
					}
				});

		final Button newDBConButton = new Button(container, SWT.NONE);
		newDBConButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				new ManageConnectionDialog(getShell(), null).open();
				fillDBCombo();
				setMessage(null);
			}

		});

		final GridData gd_newDBConButton = new GridData(SWT.FILL, SWT.TOP,
				false, false);
		newDBConButton.setLayoutData(gd_newDBConButton);
		newDBConButton.setText(Messages
				.getString("SaturnProjectNewWizardPage.create")); //$NON-NLS-1$

		final Group databaseGroup = new Group(container, SWT.NONE);
		databaseGroup.setText(Messages
				.getString("SaturnProjectNewWizardPage.datalinkmessage")); //$NON-NLS-1$
		databaseGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		final GridLayout gridLayout_2 = new GridLayout();
		gridLayout_2.numColumns = 2;
		databaseGroup.setLayout(gridLayout_2);

		final Label label_6 = new Label(databaseGroup, SWT.NONE);
		label_6.setText(Messages
				.getString("SaturnProjectNewWizardPage.databasetype")); //$NON-NLS-1$

		databaseTypeText = new Text(databaseGroup, SWT.READ_ONLY);
		final GridData gd_databaseTypeText = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		databaseTypeText.setLayoutData(gd_databaseTypeText);

		final Label label_7 = new Label(databaseGroup, SWT.NONE);
		label_7.setText(Messages
				.getString("SaturnProjectNewWizardPage.driveclassname")); //$NON-NLS-1$

		driverText = new Text(databaseGroup, SWT.READ_ONLY);
		final GridData gd_driverText = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		driverText.setLayoutData(gd_driverText);

		final Label label_8 = new Label(databaseGroup, SWT.NONE);
		label_8
				.setText(Messages
						.getString("SaturnProjectNewWizardPage.linkurl")); //$NON-NLS-1$

		urlText = new Text(databaseGroup, SWT.READ_ONLY);
		final GridData gd_urlText = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		urlText.setLayoutData(gd_urlText);

		final Label label_9 = new Label(databaseGroup, SWT.NONE);
		label_9.setText(Messages
				.getString("SaturnProjectNewWizardPage.username")); //$NON-NLS-1$

		userNameText = new Text(databaseGroup, SWT.READ_ONLY);
		final GridData gd_userNameText = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		userNameText.setLayoutData(gd_userNameText);

		final Label label_10 = new Label(databaseGroup, SWT.NONE);
		label_10.setText(Messages
				.getString("SaturnProjectNewWizardPage.passsword")); //$NON-NLS-1$

		pwdText = new Text(databaseGroup, SWT.READ_ONLY | SWT.PASSWORD);
		pwdText.setEchoChar('*');
		pwdText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		init();

		final Label serverLabel = new Label(container, SWT.NONE);
		serverLabel
				.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
		serverLabel.setText(Messages
				.getString("SaturnProjectNewWizardPage.service")); //$NON-NLS-1$

		serverCombo = new Combo(container, SWT.READ_ONLY);
		serverCombo.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				SaturnServer server = saturnServers.get(serverCombo.getText());
				updateServerInfo(server);
			}
		});
		final GridData gd_serverCombo = new GridData(SWT.FILL, SWT.TOP, true,
				false);
		serverCombo.setLayoutData(gd_serverCombo);

		final Button newServerButton = new Button(container, SWT.NONE);
		newServerButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				NewSaturnServerDialog dia = new NewSaturnServerDialog(Display
						.getDefault().getShells()[0], saturnServers);
				if (Window.OK == dia.open()) {
					String serverConfigName[] = saturnServers.keySet().toArray(
							new String[0]);
					serverCombo.setItems(serverConfigName);
					SaturnServerModel.saveSaturnServers(saturnServers);
					String serverName = dia.getSaturnServerName();
					serverCombo.select(serverCombo.indexOf(serverName));

				}
			}
		});
		newServerButton.setText(Messages
				.getString("SaturnProjectNewWizardPage.create")); //$NON-NLS-1$

		final Group serverGroup = new Group(container, SWT.NONE);
		serverGroup.setText(Messages
				.getString("SaturnProjectNewWizardPage.servicemessage")); //$NON-NLS-1$
		serverGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.numColumns = 2;
		serverGroup.setLayout(gridLayout_1);

		final Label label_1 = new Label(serverGroup, SWT.NONE);
		label_1.setText(Messages
				.getString("SaturnProjectNewWizardPage.servertype")); //$NON-NLS-1$

		serTypeText = new Text(serverGroup, SWT.READ_ONLY);
		final GridData gd_serTypeText = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		serTypeText.setLayoutData(gd_serTypeText);

		final Label label_4 = new Label(serverGroup, SWT.NONE);
		label_4.setText(Messages
				.getString("SaturnProjectNewWizardPage.webvesselurl")); //$NON-NLS-1$

		webConText = new Text(serverGroup, SWT.READ_ONLY);
		final GridData gd_webConText = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		webConText.setLayoutData(gd_webConText);

		final Label label_5 = new Label(serverGroup, SWT.NONE);
		label_5.setText(Messages
				.getString("SaturnProjectNewWizardPage.saturnserveposition")); //$NON-NLS-1$

		serLocText = new Text(serverGroup, SWT.READ_ONLY);
		final GridData gd_serLocText = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		serLocText.setLayoutData(gd_serLocText);
		fillServerCombo();
		validate();
	}

	private void fillServerCombo() {
		this.saturnServers = SaturnServerModel.getSaturnServers();
		String serverConfigName[] = saturnServers.keySet()
				.toArray(new String[0]);
		serverCombo.setItems(serverConfigName);
		if (serverConfigName.length > 0) {
			serverCombo.select(0);
			SaturnServer server = saturnServers.get(serverCombo.getText());
			updateServerInfo(server);
			setServerName(serverCombo.getText().trim());
		}
	}

	private void updateServerInfo(SaturnServer server) {
		serTypeText.setText(server.getClassType());
		webConText.setText(server.getServerPath());
		serLocText.setText(server.getDepolyPath());
	}

	public String getProjectId() {
		return conNameToId(getProjectName()) + " saturn component"; //$NON-NLS-1$
	}

	public String getVersionText() {
		return versionText.getText();
	}

	public String getProjectName() {
		return projectName.getText();
	}

	public String getCompanyName() {
		return companyName.getText();
	}

	public String getDBConnectionName() {
		return dataConCombo.getCombo().getText();
	}

	public String getSerName() {
		return serverCombo.getText();
	}

	public String conNameToId(String name) {
		String str;
		int i = name.lastIndexOf('.');
		if (i != -1) {
			str = name.substring(i + 1, name.length());
		} else {
			str = name;
		}
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	private void updateDBInfo(DBConnection dbconnection) {
		databaseTypeText.setText(dbconnection.getType());
		driverText.setText(dbconnection.getDriverClassName());
		urlText.setText(dbconnection.getUrl());
		userNameText.setText(dbconnection.getUsername());
		pwdText.setText(dbconnection.getPassword());
	}

	public boolean validate() {
		String project = this.getProjectName();
		String version = this.getVersionText();
		String company = this.getCompanyName();
		boolean isExist = false;
		IWorkspace ws = ResourcesPlugin.getWorkspace();

		IProject[] ps = ws.getRoot().getProjects();
		for (int i = 0; i < ps.length; i++) {
			IProject ipj = ps[i];
			if (project.equals(ipj.getName())) {
				isExist = true;
				break;
			}
		}

		setPageComplete(false);

		if (SaturnValidation.isEmpty(project)) {
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.0")); //$NON-NLS-1$
			return false;
		}

		if (isExist) {
			setErrorMessage(Messages
					.getString("SaturnProjectNewWizardPage.thisprojectexist")); //$NON-NLS-1$
			return false;
		}
		
		if(!SaturnValidation.isValidProgramDOtStr(project)){
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.projectNameNumberLetterUnderline")); //$NON-NLS-1$
			return false;
		}

		if (SaturnValidation.isPriNum(project)) {
			setErrorMessage(Messages
					.getString("SaturnProjectNewWizardPage.ProjcetNameStartByNumber")); //$NON-NLS-1$
			return false;
		}
		
		if(project.startsWith(Messages.getString("SaturnProjectNewWizardPage.4")) || project.endsWith(Messages.getString("SaturnProjectNewWizardPage.5"))){ //$NON-NLS-1$ //$NON-NLS-2$
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.projectNameStartAndEnd")); //$NON-NLS-1$
			return false;
			
		}

		if (SaturnValidation.isEmpty(version)) {
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.1")); //$NON-NLS-1$
			return false;
		}

		if (!SaturnValidation.isNumberDot(version)) {
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.NumberAndDot")); //$NON-NLS-1$
			return false;
		}

		if (!SaturnValidation.isPriNum(version)) {
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.StartByNumber")); //$NON-NLS-1$
			return false;
		}
		
		int size = version.length();
		int count = 0;
		
		if(SaturnValidation.isInt(version)){
			if(size>10){
				setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.NumberMaxLength")); //$NON-NLS-1$
				return false;
			}
		}
		
		String[] subVersion=version.split("\\."); //$NON-NLS-1$
		for(int i = 0; i<subVersion.length; i++){
			if(subVersion[i].length()>10){
				setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.NumberMaxLength")); //$NON-NLS-1$
				return false;
			}
		}
		
		for (int i = 0; i < size - 1; i++) {
			if ('.' == version.charAt(i)
					&& version.charAt(i) == version.charAt(i + 1)) {
				setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.DotAndDot")); //$NON-NLS-1$
				return false;
			}
		}

		for (int i = 0; i < size; i++) {
			if ('.' == (version.charAt(i))) {
				++count;
			}
		}

		if (count > 3) {
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.DotMaxNumber")); //$NON-NLS-1$
			return false;
		}
		
		if (version.endsWith(Messages.getString("SaturnProjectNewWizardPage.6"))) { //$NON-NLS-1$
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.EndWithDot")); //$NON-NLS-1$
			return false;
		}
		
		

		

		if (SaturnValidation.isEmpty(company)) {
			setErrorMessage(Messages.getString("SaturnProjectNewWizardPage.3")); //$NON-NLS-1$
			return false;
		}

		if (SaturnValidation.isBadWord(company)) {
			setErrorMessage(Messages
					.getString("SaturnProjectNewWizardPage.supplierdescriptionillegal")); //$NON-NLS-1$
			return false;
		}
		
		setErrorMessage(null);
		setPageComplete(true);
		return true;
	}

	private void fillDBCombo() {
		dataConCombo.getCombo().removeAll();
		Object aobj[] = vcp.getElements(null);
		dataConCombo.add(aobj);
		if (aobj != null && aobj.length > 0
				&& (aobj[0] instanceof DBConnection)) {
			// updateDBInfo((DBConnection) aobj[0]);
			// setDbConName(getDBConnectionName());
			dataConCombo.setSelection(new StructuredSelection(dataConCombo
					.getElementAt(aobj.length - 1)));
		}
	}

	private void init() {
		Object aobj[] = vcp.getElements(null);
		dataConCombo.add(aobj);
		if (aobj != null && aobj.length > 0
				&& (aobj[0] instanceof DBConnection)) {
			// dataConCombo.setSelection(new StructuredSelection(aobj[0]));
			// updateDBInfo((DBConnection) aobj[0]);
			// setDbConName(getDBConnectionName());
			dataConCombo.setSelection(new StructuredSelection(dataConCombo
					.getElementAt(0)));// .getElementAt(aobj.length - 1)
		}
	}

	public String getDbConName() {
		return dbConName;
	}

	public void setDbConName(String dbConName) {
		this.dbConName = dbConName;
	}

	public String getServerName() {
		return serverName;
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}
}
